package com.gopay.gass.web.controller.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.PayBankOpType;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.cbrmb.Tran01734VO;
import com.gopay.common.domain.cps.cbrmb.Tran01734VO.Action;
import com.gopay.common.domain.cps.transfer.Tran00700VO;
import com.gopay.common.domain.cps.vo.CPSRequest;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.exception.GopayException;
import com.gopay.gass.web.controller.BaseController;
import com.gopay.remote.cps.dispatch.CPSCallRemoteService;

//@Controller
@RequestMapping("/notify")
public class NotifyControllerImpl extends BaseController{
	// 2017-10-13起作废 生产优化10期 基于httpclient 调用方式被替换为 hessian 见 remote.xml 中的 /pay
    // 2017-10-13后 远程调用地址为 GassPayRemoteService 接口中的  GassBcdlNotifyRespMessage bcdlNotifyGass(Map<String, String> param);
	@Resource(name = "cpsClient")
	protected CPSCallRemoteService cpsClient;
	
	@Resource(name = "cbrCpsClient")
    protected CPSCallRemoteService cbrCpsClient;
	
	@Resource(name="cpsGeneralMainOrderQueryDAO")
	protected CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderQueryDAO;
	
	@RequestMapping(value = { "/bcdlNotify.shtml" })
    public ModelAndView bcdlNotify(HttpServletRequest request, HttpServletResponse response, int resultCode, String resultMsg, String gopayOrderId
    		, String remark) {
		CpsGenMainOrder main=cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class, gopayOrderId);
		if(main!=null&&IntTxnCd._01734.value.equals(main.getGopayIntTxnCd())){
		    CPSResponse cpsResponse = null;
		    //通知cbrcps修改拨款订单的状态
		    Tran01734VO vo=new Tran01734VO();
		    vo.setAction(Action.END);
		    vo.setGopayOrderId(gopayOrderId);
		    vo.setResultCode(resultCode);
            vo.setResultMsg(resultMsg);
            
            // 封装调用cps服务的请求baggage
            Map<String, Object> baggage = new HashMap<String, Object>();
            baggage.put("s", "0");
            baggage.put("t", "001");
            baggage.put("v", vo);

            // 封装cps请求对象
            CPSRequest cpsRequest = new CPSRequest();
            cpsRequest.setSequence(System.currentTimeMillis());
            cpsRequest.setReqData(baggage);
            logger.error("gass收到bis通知。CPSRequest=" + ToStringBuilder.reflectionToString(cpsRequest));
            logger.info("订单号:"+gopayOrderId+"收到的结果resultCode="+resultCode);
           //调跨境的cbrcps
            cpsResponse = cbrCpsClient.callCPS(cpsRequest);

            // 校验调用序列值是否相同
            if (cpsResponse.getSequence() != cpsRequest.getSequence()) {
                super.handleError(response, ProcCodeConstants.PROC_CODE_100F3001);
            }
            logger.error("银行处理结束，CPS后续处理结果：" + cpsResponse.getRespCode() + "; gopayOrderId=" + gopayOrderId);
                try {
                    super.resp2Bis(response, "UTF-8", cpsResponse.getRespCode());
                } catch (GopayException e) {
                    // TODO Auto-generated catch block
                  logger.info("",e);
                }

		}else{
		CPSResponse cpsResponse = null;

        try {
        	Tran00700VO pay = new Tran00700VO();
			pay.setOpType(PayBankOpType.PAY_END);//Bis处理完成，付款成功：账务处理
			pay.setGopayOrderId(gopayOrderId);
			pay.setResultCode(resultCode);
			pay.setResultMsg(resultMsg);
//			pay.setRemark(remark);
			String needRefund = request.getParameter("needRefund");
			if("1".equals(needRefund)){
				pay.setNeedRefund(needRefund);
			}
			
            // 封装调用cps服务的请求baggage
            Map<String, Object> baggage = new HashMap<String, Object>();
            baggage.put("s", "0");
            baggage.put("t", "001");
            baggage.put("v", pay);

            // 封装cps请求对象
            CPSRequest cpsRequest = new CPSRequest();
            cpsRequest.setSequence(System.currentTimeMillis());
            cpsRequest.setReqData(baggage);
            logger.error("gass收到bis通知。CPSRequest=" + ToStringBuilder.reflectionToString(cpsRequest));
            cpsResponse = cpsClient.callCPS(cpsRequest);

            // 校验调用序列值是否相同
            if (cpsResponse.getSequence() != cpsRequest.getSequence()) {
                super.handleError(response, ProcCodeConstants.PROC_CODE_100F3001);
            }
            logger.error("银行处理结束，CPS后续处理结果：" + cpsResponse.getRespCode() + "; gopayOrderId=" + gopayOrderId);
//            if(ProcCodeConstants.PROC_CODE_100S1000.equals(cpsResponse.getRespCode())) {
//            	super.resp2Bis(response, "UTF-8", "0000");
//            } else {
            	super.resp2Bis(response, "UTF-8", cpsResponse.getRespCode());
//            }
            
        } catch (Exception e) {
            logger.error("CallCPSUtil.", e);
            super.handleError(response, ProcCodeConstants.PROC_CODE_100F3001);
        }
		}
        return null;
    }
}
